package cn.myapps.msg.sender;

import cn.myapps.msg.DefaultTemplate;
import cn.myapps.msg.PushControl;
import cn.myapps.msg.enums.MsgStatusEnum;
import cn.myapps.msg.vo.MailFile;
import cn.myapps.msg.mail.entity.MailTemplate;
import cn.myapps.msg.mail.entity.MsgMail;
import cn.myapps.msg.mail.service.IMailTemplateService;
import cn.myapps.msg.mail.service.IMsgMailService;
import cn.myapps.msg.maker.MailMsgMaker;
import cn.myapps.msg.service.IMailService;
import cn.myapps.msg.vo.MsgCommon;
import cn.myapps.msg.vo.SendResult;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jeecg.common.util.SpringContextUtils;

import java.io.File;
import java.util.List;

/**
 * @Description: E-Mail发送器
 * @Author: nicholas
 * @Date:   2020-06-10
 * @Version: V1.0
 */
@Slf4j
public class MailMsgSender implements IMsgSender {

    private MailMsgMaker mailMsgMaker;

    private IMailTemplateService mailTemplateService;
    private IMsgMailService msgMailService;
    private IMailService mailService;


    public MailMsgSender() {
        mailTemplateService = SpringContextUtils.getBean(IMailTemplateService.class);
        msgMailService = SpringContextUtils.getBean(IMsgMailService.class);
        mailService = SpringContextUtils.getBean(IMailService.class);

        mailMsgMaker = new MailMsgMaker();
    }

    @Override
    public SendResult send(MsgCommon msg) {
        try {
            mailMsgMaker.prepare(new DefaultTemplate());
            List<MsgMail> mails = mailMsgMaker.makeMsg(msg);
            return doSend(mails, msg);
        } catch (Exception e) {
            SendResult sendResult = new SendResult();
            sendResult.setSuccess(false);
            sendResult.setInfo(e.getMessage());
            log.error(ExceptionUtils.getStackTrace(e));

            return sendResult;
        }
    }

    @Override
    public SendResult sendByTemplate(MsgCommon msg) {
        try {
            MailTemplate template = mailTemplateService.findByCode(msg.getTemplateCode());
            mailMsgMaker.prepare(template);
            List<MsgMail> mails = mailMsgMaker.makeMsg(msg);
            return doSend(mails, msg);
        } catch (Exception e) {
            SendResult sendResult = new SendResult();

            sendResult.setSuccess(false);
            sendResult.setInfo(e.getMessage());
            log.error(ExceptionUtils.getStackTrace(e));

            return sendResult;
        }
    }

    private SendResult doSend(List<MsgMail> mails, MsgCommon msg){
        SendResult sendResult = new SendResult();

        if (PushControl.dryRun) {
            sendResult.setSuccess(true);
            return sendResult;
        } else {
            boolean hasCc = false; // 多个邮件只抄送一次

            for (MsgMail mail : mails) { // 循环发送
                List<String> ccList = null;
                if (StringUtils.isNotBlank(mail.getCc()) && !hasCc) {
                    ccList = Lists.newArrayList();
                    ccList.add(mail.getCc());
                    hasCc = true;
                }
                try {
                    if (StringUtils.isEmpty(mail.getFileJson())) {
                        mailService.sendHtmlMail(mail.getMsgFrom(), mail.getMsgTo(), mail.getTitle(), mail.getContent());
                    } else {
                        List<MailFile> files = JSON.parseArray(mail.getFileJson(), MailFile.class);
                        mailService.sendUriAttachmentsMail(mail.getMsgFrom(), mail.getMsgTo(), mail.getTitle(), mail.getContent(), files);
                    }

                    // 变更状态并保存到数据库
                    mail.setMsgStatus(MsgStatusEnum.SENED.getCode());
                } catch (Exception ex) {
                    log.error("邮件消息发送失败", ex);
                    mail.setMsgStatus(MsgStatusEnum.UNSENED.getCode());
                }

                msgMailService.save(mail);
            }

            sendResult.setSuccess(true);
        }

        return sendResult;
    }

    @Override
    public SendResult asyncSend(MsgCommon msg) {
        throw new UnsupportedOperationException("不支持异步发送模式");
    }

    public SendResult sendTestMail(String tos) {
        SendResult sendResult = new SendResult();

        try {
            mailService.sendHtmlMail("default", tos, "这是一封来自MyApps的测试邮件",
                    "<h1>恭喜，配置正确，邮件发送成功！</h1><p>来自MyApps，一款专注于消息推送的微服务。</p>");

            sendResult.setSuccess(true);
        } catch (Exception e) {
            sendResult.setSuccess(false);
            sendResult.setInfo(e.getMessage());
            log.error(e.toString());
        }

        return sendResult;
    }

    /**
     * 发送推送结果
     *
     * @param tos
     * @return
     */
    public SendResult sendPushResultMail(String tos, String title, String content, File[] files) {
        SendResult sendResult = new SendResult();

        try {
            mailService.sendHtmlMail("default", tos, title, content);
            sendResult.setSuccess(true);
        } catch (Exception e) {
            sendResult.setSuccess(false);
            sendResult.setInfo(e.getMessage());
            log.error(e.toString());
        }

        return sendResult;
    }
}
